package com.cyy.common.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyy.common.constant.Constants;
import com.cyy.common.mapper.ArticleLikeMapper;
import com.cyy.common.mapper.ArticleMapper;
import com.cyy.common.pojo.vo.system.SystemArticleLikeVo;
import com.cyy.common.pojo.entity.Article;
import com.cyy.common.pojo.entity.ArticleLike;
import com.cyy.common.pojo.query.system.SystemArticleLikeQuery;
import com.cyy.common.service.ArticleLikeService;
import com.cyy.common.utils.PageUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p>
 * 文章点赞表 服务实现类
 * </p>
 *
 * @author 曹云友
 * @since 2024-04-01
 */
@Service
@RequiredArgsConstructor
public class ArticleLikeServiceImpl extends ServiceImpl<ArticleLikeMapper, ArticleLike> implements ArticleLikeService {

    private final ArticleMapper articleMapper;

    @Override
    public IPage<SystemArticleLikeVo> getPage(SystemArticleLikeQuery query) {
        return baseMapper.getPage(PageUtils.getPage(),
                query,
                StpUtil.getLoginIdAsInt());
    }

    @Override
    public void like(Integer id) {
        // 查询是否存在点赞记录
        ArticleLike one = getOne(Wrappers.<ArticleLike>lambdaQuery()
                .eq(ArticleLike::getArticleId, id)
                .eq(ArticleLike::getUserId, StpUtil.getLoginIdAsInt())
                .last(Constants.LIMIT_1)
        );
        if (Objects.isNull(one)) {
            one = new ArticleLike();
            one.setArticleId(id);
            one.setUserId(StpUtil.getLoginIdAsInt());
            save(one);
            articleMapper.update(Wrappers.<Article>lambdaUpdate()
                    .setSql("like_count = like_count + 1")
                    .eq(Article::getId, id));
        } else {
            remove(Wrappers.<ArticleLike>lambdaQuery()
                    .eq(ArticleLike::getArticleId, id)
                    .eq(ArticleLike::getUserId, StpUtil.getLoginIdAsInt())
            );
            articleMapper.update(Wrappers.<Article>lambdaUpdate()
                    .setSql("like_count = like_count - 1")
                    .eq(Article::getId, id));
        }
    }
}
